/**
 * FrameAnimation 测试示例
 *
 * 这个文件展示了帧动画系统的各种使用方式：
 * 1. 预设动画（开箱即用）
 * 2. 自定义帧动画
 * 3. 命令式控制
 * 4. 平滑过渡效果
 * 5. 自定义帧渲染
 */

import React, { useRef, useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, ScrollView } from 'react-native';
import {
  FrameAnimationController,
  VoicePlayingAnimation,
  TypingAnimation,
  VoicePlayingFrames,
} from './components/FrameAnimation';
import type { FrameAnimationControllerRef } from './components/FrameAnimation';

// ==================== 示例1: 预设动画（最简单） ====================

const Example1_PresetAnimations = () => {
  const [isVoicePlaying, setIsVoicePlaying] = useState(false);
  const [isTyping, setIsTyping] = useState(false);

  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例1: 预设动画（开箱即用）</Text>

      {/* 语音播放动画 */}
      <View style={styles.animationRow}>
        <View style={styles.animationBox}>
          <VoicePlayingAnimation playing={isVoicePlaying} color="#007AFF" size="medium" />
        </View>
        <TouchableOpacity style={styles.button} onPress={() => setIsVoicePlaying(!isVoicePlaying)}>
          <Text style={styles.buttonText}>{isVoicePlaying ? '暂停语音' : '播放语音'}</Text>
        </TouchableOpacity>
      </View>

      {/* 正在输入动画 */}
      <View style={styles.animationRow}>
        <View style={styles.animationBox}>
          <TypingAnimation playing={isTyping} color="#999999" size="medium" />
        </View>
        <TouchableOpacity style={styles.button} onPress={() => setIsTyping(!isTyping)}>
          <Text style={styles.buttonText}>{isTyping ? '停止输入' : '开始输入'}</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

// ==================== 示例2: 不同尺寸和颜色 ====================

const Example2_Variants = () => {
  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例2: 不同尺寸和颜色</Text>

      {/* 小号蓝色 */}
      <View style={styles.animationRow}>
        <Text style={styles.label}>小号蓝色:</Text>
        <VoicePlayingAnimation playing={true} color="#007AFF" size="small" />
      </View>

      {/* 中号绿色 */}
      <View style={styles.animationRow}>
        <Text style={styles.label}>中号绿色:</Text>
        <VoicePlayingAnimation playing={true} color="#34C759" size="medium" />
      </View>

      {/* 大号红色 */}
      <View style={styles.animationRow}>
        <Text style={styles.label}>大号红色:</Text>
        <VoicePlayingAnimation playing={true} color="#FF3B30" size="large" />
      </View>

      {/* 自定义尺寸 */}
      <View style={styles.animationRow}>
        <Text style={styles.label}>自定义尺寸:</Text>
        <VoicePlayingAnimation playing={true} color="#FF9500" barWidth={5} maxHeight={30} gap={6} size="large" />
      </View>
    </View>
  );
};

// ==================== 示例3: 命令式控制 ====================

const Example3_ImperativeControl = () => {
  const animRef = useRef<FrameAnimationControllerRef>(null);
  const [currentFrame, setCurrentFrame] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);

  const asyncFrameChange = (frame: number) => {
    setTimeout(() => {
      setCurrentFrame(frame);
    }, 100);
  };

  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例3: 命令式控制（ref）</Text>

      {/* 动画显示 */}
      <View style={styles.animationBox}>
        <FrameAnimationController
          ref={animRef}
          frameCount={3}
          frameDuration={200}
          onFrameChange={frame =>asyncFrameChange(frame)}
          onPlayStart={() => setIsPlaying(true)}
          onPause={() => setIsPlaying(false)}
        >
          {frame => <VoicePlayingFrames currentFrame={frame} color="#007AFF" maxHeight={24} />}
        </FrameAnimationController>
      </View>

      <Text style={styles.statusText}>
        当前帧: {currentFrame} | 状态: {isPlaying ? '播放中' : '已暂停'}
      </Text>

      {/* 控制按钮 */}
      <View style={styles.controlGrid}>
        <TouchableOpacity style={styles.controlButton} onPress={() => animRef.current?.play()}>
          <Text style={styles.buttonText}>播放</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.controlButton} onPress={() => animRef.current?.pause()}>
          <Text style={styles.buttonText}>暂停</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.controlButton} onPress={() => animRef.current?.stop()}>
          <Text style={styles.buttonText}>停止</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.controlButton} onPress={() => animRef.current?.toggle()}>
          <Text style={styles.buttonText}>切换</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.controlButton} onPress={() => animRef.current?.prevFrame()}>
          <Text style={styles.buttonText}>上一帧</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.controlButton} onPress={() => animRef.current?.nextFrame()}>
          <Text style={styles.buttonText}>下一帧</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.controlButton} onPress={() => animRef.current?.goToFrame(0)}>
          <Text style={styles.buttonText}>跳到帧0</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.controlButton} onPress={() => animRef.current?.goToFrame(2)}>
          <Text style={styles.buttonText}>跳到帧2</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

// ==================== 示例4: 平滑过渡对比 ====================

const Example4_SmoothTransition = () => {
  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例4: 平滑过渡效果对比</Text>

      {/* 离散切换（默认） */}
      <View style={styles.animationRow}>
        <Text style={styles.label}>离散切换:</Text>
        <VoicePlayingAnimation playing={true} color="#007AFF" smoothTransition={false} frameDuration={300} />
      </View>

      {/* 平滑过渡 */}
      <View style={styles.animationRow}>
        <Text style={styles.label}>平滑过渡:</Text>
        <VoicePlayingAnimation playing={true} color="#34C759" smoothTransition={true} frameDuration={300} />
      </View>
    </View>
  );
};

// ==================== 示例5: 自定义帧渲染 ====================

const Example5_CustomFrames = () => {
  // 自定义帧数据：一个简单的旋转方块动画
  const renderCustomFrame = (frameIndex: number) => {
    const rotations = ['0deg', '90deg', '180deg', '270deg'];
    const colors = ['#FF3B30', '#FF9500', '#FFCC00', '#34C759'];

    return (
      <View
        style={{
          width: 30,
          height: 30,
          backgroundColor: colors[frameIndex],
          transform: [{ rotate: rotations[frameIndex] }],
        }}
      />
    );
  };

  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例5: 自定义帧渲染</Text>

      <View style={styles.animationBox}>
        <FrameAnimationController
          frameCount={4}
          frameDuration={250}
          autoPlay={true}
          loop={true}
          smoothTransition={true}
        >
          {renderCustomFrame}
        </FrameAnimationController>
      </View>

      <Text style={styles.description}>完全自定义的旋转方块动画，展示了帧系统的灵活性</Text>
    </View>
  );
};

// ==================== 示例6: 聊天场景应用 ====================

interface MessageItem {
  id: number;
  type: 'text' | 'voice';
  content?: string;
  duration?: number;
  isSent: boolean;
  isPlaying?: boolean;
}

const Example6_ChatScenario = () => {
  const [messages, setMessages] = useState<MessageItem[]>([
    { id: 1, type: 'text', content: '你好！', isSent: true },
    { id: 2, type: 'voice', duration: 3, isSent: false, isPlaying: false },
    { id: 3, type: 'text', content: '收到', isSent: true },
  ]);
  const [isTyping, setIsTyping] = useState(true);

  const toggleVoicePlaying = (id: number) => {
    setMessages(prev =>
      prev.map(msg => (msg.id === id && msg.type === 'voice' ? { ...msg, isPlaying: !msg.isPlaying } : msg)),
    );
  };

  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例6: 聊天场景应用</Text>

      <View style={styles.chatContainer}>
        {messages.map(msg => {
          if (msg.type === 'text') {
            return (
              <View key={msg.id} style={[styles.messageBubble, msg.isSent ? styles.sentBubble : styles.receivedBubble]}>
                <Text style={[styles.messageText, msg.isSent ? styles.sentText : styles.receivedText]}>
                  {msg.content}
                </Text>
              </View>
            );
          } else if (msg.type === 'voice') {
            return (
              <TouchableOpacity
                key={msg.id}
                style={[
                  styles.messageBubble,
                  styles.voiceBubble,
                  msg.isSent ? styles.sentBubble : styles.receivedBubble,
                ]}
                onPress={() => toggleVoicePlaying(msg.id)}
              >
                <VoicePlayingAnimation
                  playing={msg.isPlaying}
                  color={msg.isSent ? '#FFFFFF' : '#007AFF'}
                  size="small"
                />
                <Text style={[styles.voiceDuration, msg.isSent ? styles.sentText : styles.receivedText]}>
                  {msg.duration}"
                </Text>
              </TouchableOpacity>
            );
          }
          return null;
        })}

        {/* 正在输入指示器 */}
        {isTyping && (
          <View style={[styles.messageBubble, styles.receivedBubble]}>
            <TypingAnimation playing={true} color="#999999" size="small" />
          </View>
        )}
      </View>

      <TouchableOpacity style={styles.button} onPress={() => setIsTyping(!isTyping)}>
        <Text style={styles.buttonText}>{isTyping ? '停止输入提示' : '显示输入提示'}</Text>
      </TouchableOpacity>
    </View>
  );
};

// ==================== 主应用 ====================

export const TestFrameAnimation = () => {
  return (
    <ScrollView contentContainerStyle={styles.scrollContent}>
      <Text style={styles.mainTitle}>FrameAnimation 测试示例</Text>

      <Example1_PresetAnimations />
      <Example2_Variants />
      <Example3_ImperativeControl />
      <Example4_SmoothTransition />
      <Example5_CustomFrames />
      <Example6_ChatScenario />

      <View style={styles.footer}>
        <Text style={styles.footerText}>🎉 帧动画系统测试完成！</Text>
      </View>
    </ScrollView>
  );
};

// ==================== 样式 ====================

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
  },
  scrollContent: {
    padding: 16,
  },
  mainTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#000',
    textAlign: 'center',
    marginBottom: 24,
  },
  exampleContainer: {
    backgroundColor: '#FFF',
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  exampleTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#000',
    marginBottom: 16,
  },
  animationRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
    gap: 12,
  },
  animationBox: {
    padding: 12,
    backgroundColor: '#F9F9F9',
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
    minWidth: 60,
    minHeight: 40,
  },
  label: {
    fontSize: 14,
    color: '#666',
    minWidth: 100,
  },
  button: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 8,
    flex: 1,
  },
  buttonText: {
    color: '#FFF',
    fontSize: 14,
    fontWeight: '500',
    textAlign: 'center',
  },
  statusText: {
    fontSize: 14,
    color: '#666',
    textAlign: 'center',
    marginVertical: 12,
  },
  controlGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  controlButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 6,
    width: '48%',
  },
  description: {
    fontSize: 12,
    color: '#999',
    textAlign: 'center',
    marginTop: 8,
  },
  chatContainer: {
    backgroundColor: '#F9F9F9',
    borderRadius: 8,
    padding: 12,
    minHeight: 200,
    marginBottom: 12,
  },
  messageBubble: {
    maxWidth: '70%',
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 16,
    marginBottom: 8,
  },
  sentBubble: {
    alignSelf: 'flex-end',
    backgroundColor: '#007AFF',
  },
  receivedBubble: {
    alignSelf: 'flex-start',
    backgroundColor: '#E5E5EA',
  },
  messageText: {
    fontSize: 16,
  },
  sentText: {
    color: '#FFF',
  },
  receivedText: {
    color: '#000',
  },
  voiceBubble: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    minWidth: 80,
  },
  voiceDuration: {
    fontSize: 14,
    fontWeight: '500',
  },
  footer: {
    alignItems: 'center',
    padding: 24,
  },
  footerText: {
    fontSize: 16,
    color: '#666',
  },
});
